import {connect} from "react-redux";
import {AtIcon, AtSearchBar} from 'taro-ui'
import {ComponentClass} from 'react'
import React, { Component } from 'react';
import Taro, { Config } from '@tarojs/taro';
import Skeleton from 'taro-skeleton'
import {Block, Image, Navigator, ScrollView, View} from '@tarojs/components'
import {CityLocation} from '../utils/server.interface'
import {http} from '../utils/http'
import {
  LIMIT_FROM_SELLER_SINCE,
  MOVIE_CINEMAS,
  MOVIE_CITY,
  MOVIE_MOVIES,
  RESOURCE_URL,
  SCAN_BIND_SELLER,
  SHARE_PIC,
  TARO_ENV
} from '../constants/api'
import Headerbar from "./header-bar/header-bar";
import {getHeadTop, GetRequest, getTempSellerId, setTempSellerId} from "../utils/tools";
import Cinema from "./cinema/cinema";
import Screen from "./cinema/screen";
import {platform} from "../utils/platform-settting.service";
import {user} from "../utils/user.service";
import {location} from "../utils/location.service";
import {getMoviePoster} from "../utils/poster.service";
import {h5Wx} from "../utils/h5.service";
import GzhAuth from "../components/gzh-auth/gzh-auth"
import './index.scss'

type PageStateProps = {
  location: CityLocation
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  loadMoreStatus: "more" | "loading" | "noMore"
  searchKey: string
  cinemaList: any
  tempSellerId: any
  regionList: any
  movieList: any
  searchBarTop: number
  location: any
  ML: any
  sort: number
  regionId: number
  check: number
  imageUrl: string
  isLogin: boolean
  shareName: string
  slogan: string
  loading: boolean
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Movie {
  props: IProps
}

@connect(({location}) => ({
  location,
}), () => ({}))
class Movie extends Component {
  state: PageState = {
    loadMoreStatus: 'loading',
    movieList: [],
    cinemaList: [],
    regionList: [],
    searchKey: '',
    tempSellerId: '',
    searchBarTop: 0,
    location: {region_id: 0, area_name: '未知'},
    ML: {},
    isLogin: false,
    sort: 0,
    regionId: 0,
    check: 0,
    imageUrl: '',
    shareName: '',
    slogan: '',
    loading: true
  }
  page = 1
  shareParams = ''

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 40) : (headTop.statusBar + headTop.top + 40)
    this.setState({searchBarTop})
    const platformSet = await platform.getSetting()
    const scene = Taro.getCurrentInstance().router.params.scene as string | undefined;
    let bindSellerId = Taro.getStorageSync('bindSellerId') || 0;
    let bindSellerIds = Taro.getCurrentInstance().router.params.bindSellerId || ''
    let tempSellerIds = Taro.getCurrentInstance().router.params.tempSellerId || ''
    if (scene && (/^\d+_\d+$/.test(scene) || /^\d+_\d+_\d+$/.test(scene))) {
      platform.scene = 0;
      const paramArr = scene.split('_');
      if (platformSet.isSellerPermanentLock) {
        if (!bindSellerId) {
          bindSellerId = paramArr[1];
        }
      } else {
        bindSellerId = paramArr[1];
      }
      if (paramArr[1]) {
        bindSellerIds = paramArr[1]
      }
      if (paramArr[2]) {
        tempSellerIds = paramArr[2]
        setTempSellerId(paramArr[2])
        this.setState({tempSellerId: paramArr[2]})
      }
    } else {
      const tempSellerId = getTempSellerId(this)
      this.setState({tempSellerId})
      if (platformSet.isSellerPermanentLock) {
        if (!bindSellerId) {
          bindSellerId = Taro.getCurrentInstance().router.params.bindSellerId || bindSellerId;
        }
      } else {
        bindSellerId = Taro.getCurrentInstance().router.params.bindSellerId || bindSellerId;
      }
    }
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, { temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds });
    }
    user.bindSellerId = bindSellerId
    Taro.setStorage({
      key: 'bindSellerId',
      data: user.bindSellerId,
    })
    Taro.showLoading({
      title: "加载中"
    })
    if (bindSellerId && TARO_ENV !== 'h5') {
      Taro.login({
        success: async (res) => {
          if (res.code) {
            const integralForm = {
              sellerId: bindSellerId,
              code: res.code
            }
            await http.post(LIMIT_FROM_SELLER_SINCE, integralForm);
          }
        }
      })
    }
    const ret = await http.MGet(MOVIE_CITY, {})
    const city = Taro.getStorageSync('city')
    for (const i of ret) {
      if (city && city.area_name.includes(i['city_name'])) {
        Taro.setStorageSync("Mlocation", {"region_id": i.city_id, "area_name": i['city_name']})
        break
      }
    }
    const mLocation = Taro.getStorageSync("Mlocation") || {region_id: 0, area_name: '未知'};
    const ML = Taro.getStorageSync("ML");
    if (mLocation.region_id == 0 || mLocation.region_id == undefined || !ML) {
      await this.getLocation()
    } else {
      await this.initData(mLocation, ML)
    }
    Taro.hideLoading()
  }

  async componentDidShow() {
    if (!this.state.loading) {
      const mLocation = Taro.getStorageSync("Mlocation") || {region_id: 0, area_name: '未知'};
      const ML = Taro.getStorageSync("ML");
      if (mLocation) {
        this.initData(mLocation, ML)
      }
    }

    const isLogin = await user.checkLogin()
    if (isLogin) {
      this.shareParams = await user.getSellerParams()
      this.setState({isLogin})
      const res = await http.postCar(SHARE_PIC, {})
      if (res) {
        this.setState({
          imageUrl: res.sharePic,
          shareName: res.shortName,
          slogan: res.slogan
        })
      }
    }
  }

  async initData(location, ML) {
    this.setState({location, ML})
    const ret = await this.getList(location.region_id, ML)
    if (ret) {
      this.setState({
        movieList: ret.movieList,
        loading: false,
      })
    }
    const msg = await this.getData(this.page, location.region_id, ML)
    if (msg) {
      this.setState({
        cinemaList: msg.cinemaList
      })
    }
  }

  async getList(cityId, ML) {
    const data = {type: 1, cityId, lng: ML.lng, lat: ML.lat}
    return await http.MGet(MOVIE_MOVIES, data)
  }

  async getData(page, cityId, ML, regionId?) {
    const {sort} = this.state
    let data = {page, count: 20, cityId, lng: ML.lng, lat: ML.lat, sort: sort ? 'price_asc' : 'distance_asc'}
    if (regionId) {
      data = {page, count: 20, cityId, lng: ML.lng, lat: ML.lat, sort: sort ? 'price_asc' : 'distance_asc', regionId}
    }
    const List = await http.MGet(MOVIE_CINEMAS, data)
    if (List && List.cinemaList.length >= 20) {
      this.setState({loadMoreStatus: 'more'})
    } else {
      this.setState({loadMoreStatus: 'noMore'})
    }
    return List
  }

  async searchConfirm() {
    Taro.navigateTo({
      url: '/movie/Mlist?' + this.shareParams
    })
  }

  async getLocation() {
    try {
      location.getLocation().then(async (res: any) => {
        if (res == null) {
          console.log('不是微信浏览器');
        } else {
          if (process.env.TARO_ENV === 'h5') {
            Taro.setStorageSync("ML", {lng: res.longitude, lat: res.latitude})
            const city = await location.getLocationNewH5City(res.longitude, res.latitude, 'wgs84')
            if (city) {
              this.checkCity(city.area_name, {lng: res.longitude, lat: res.latitude})
            }
          } else {
            Taro.setStorageSync("ML", {lng: res.longitude, lat: res.latitude})
            const city = await location.getLocationCity(res.longitude, res.latitude)
            if (city) {
              this.checkCity(city.area_name, {lng: res.longitude, lat: res.latitude})
            }
          }
        }
      });
    } catch (e) {
      Taro.showModal({
        title: '提示',
        content: '您需要开启手机的GPS定位, 才能为您匹配精准的信息',
        success: () => {
          Taro.navigateBack({ delta: 1 })
        },
        fail: () => {
          Taro.navigateBack({ delta: 1 })
        }
      })
    }
  }

  async checkCity(str) {
    const ret = await http.MGet(MOVIE_CITY, {})
    if (ret) {
      let val = {}
      ret.map(item => {
        if (str.indexOf(item.city_name) > -1) {
          val = {region_id: item.city_id, area_name: item.city_name}
        }
      })
      if (val.region_id) {
        Taro.setStorageSync("Mlocation", val)
        Taro.redirectTo({
          url: '/movie/index'
        })
      } else {
        Taro.showToast({
          title: '获取城市失败！请手动定位',
          icon: 'none',
          duration: 2000,
        })
        setTimeout(function () {
          Taro.navigateTo({
            url: "/other/select-city/movie-city"
          })
        }, 2000)
      }
    } else {
      Taro.navigateTo({
        url: "/other/select-city/movie-city"
      })
    }
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.cinemaList
      const {location, ML, regionId} = this.state
      this.page++
      const msg = await this.getData(this.page, location.region_id, ML, regionId)
      if (msg) {
        const newData = msg.cinemaList
        this.setState({cinemaList: [...old, ...newData]})
      }
    }
  }

  goBuy(id) {
    Taro.navigateTo({
      url: "/movie/Minfo?id=" + id
    })
  }

  async onOther(e) {
    const {location, ML} = this.state
    this.setState({
      regionId: e
    })
    const msg = await this.getData(this.page, location.region_id, ML, e)
    if (msg) {
      this.setState({
        cinemaList: msg.cinemaList
      })
    }
  }

  async onCOther(e) {
    const that = this
    const {location, regionId} = this.state
    const ML = Taro.getStorageSync("ML");
    this.setState({
      sort: e
    }, async () => {
      const msg = await that.getData(that.page, location.region_id, ML, regionId)
      if (msg) {
        that.setState({
          cinemaList: msg.cinemaList
        })
      }
    })
  }

  async getPoste() {
    const isLogin = await user.checkLogin();
    if (!isLogin) {
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 500);
      return
    }
    const that = this
    const data = this.state.slogan
    if (data) {
      Taro.setClipboardData({
        data,
        success: ()=> {
          Taro.showToast({ title: '成功复制广告语' })
          setTimeout(async ()=>{
            await that.onGetPoster()
          },1500)
        }
      })
    } else {
      await that.onGetPoster()
    }
  }

  async onGetPoster() {
    Taro.showLoading({title: '获取海报中...'});
    const shareParams = await user.getMovieSellerParams(this.state.tempSellerId || getTempSellerId(this))
    const poster = await getMoviePoster({path: 'movie/index', scene: shareParams, pageType: 'index', tempSellerId: this.state.tempSellerId || getTempSellerId(this)})
    Taro.hideLoading();
    if (poster) {
      Taro.navigateTo({url: '/distributor/poster/poster?url=' + poster.url})
    } else {
      Taro.showToast({title: '获取海报失败！', icon: 'none'})
    }
  }

  onShareAppMessage() {
    const {imageUrl, shareName} = this.state
    if (imageUrl) {
      return {
        path: '/movie/index?' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
        title: shareName ? shareName : '想看特价电影，就来购吧！',
        imageUrl
      };
    } else {
      return {
        path: '/movie/index?' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
        title: shareName ? shareName : '想看特价电影，就来购吧！',
      };
    }

  }

  render() {
    const {
      location,
      searchBarTop,
      searchKey,
      movieList,
      cinemaList,
      check,
      isLogin,
    } = this.state
    return (
      <View className='moveList'>
        <GzhAuth />
        <View className='head-bg' style={`height: ${searchBarTop}Px;`}>
          <Headerbar title='电影' />
        </View>
        <View className='haeder'>
          <Navigator className='add-city' url='/other/select-city/movie-city' hoverClass='none'>
            {location.area_name}
          </Navigator>
          <View className='search-box' onClick={this.searchConfirm.bind(this)}>
            <AtSearchBar className='search' disabled value={searchKey} placeholder='搜索电影' />
          </View>
        </View>
        {location && !!location.region_id &&
        <Block>
          <View className='hot-box'>
            <View className='hot-title'>热门影片<Navigator url='/movie/Mlist' hoverClass='none'
              className='hot-more'
            >查看更多<AtIcon
              value='chevron-right' size='12' color='#a0a0a0'
            /></Navigator></View>
            <Skeleton loading={!movieList || movieList.length == 0}
              title
              titleWidth='100%' rowHeight='120px'
            >
              <ScrollView scrollX enable-flex className='subNav'>
                <View className='hot-list'>
                  {movieList && movieList.length > 0 && movieList.map((item, index) =>
                    <View className='hot-item' key={index} onClick={this.goBuy.bind(this, item.std_id)}>
                      <Image className='hot-img' src={RESOURCE_URL + item.poster} mode='aspectFill' />
                      <View className='hot-text'>{item.name}</View>
                    </View>
                  )}
                </View>
              </ScrollView>
            </Skeleton>
          </View>
          <View className='cinema-box'>
            <View className='cinema-title'>影院</View>
          </View>
          <View className='screenBox' style={`top: ${searchBarTop}Px;`}>
            <Screen key='index' id='screen' onOther={this.onOther.bind(this)} onCOther={this.onCOther.bind(this)}
              check={check} borderColor='#f1f1f1' searchBarTop={searchBarTop}
            />
          </View>
          <Skeleton loading={!cinemaList || cinemaList.length == 0} row={4} rowHeight={150}>
            <Cinema go={0} data={cinemaList} />
          </Skeleton>
          {isLogin && <View className='sharebox' onClick={this.getPoste.bind(this)}><Image
            src='https://resource.ivcheng.com/upload/file/9da1bf81cbdd4f3399f4ff6a0e1f1a35.png'
            className='imageClass'
          />分享好友</View>}
        </Block>
        }
      </View>
    )
  }
}

export default Movie as ComponentClass<PageOwnProps, PageState>
